from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional, List, Dict, Any
from datetime import datetime

from schemas.operation_log import OperationLog
from models import OperationLog as OperationLogModel
from database import get_db

router = APIRouter()


@router.get("/", response_model=Dict[str, Any])
def get_operation_logs(
    db: Session = Depends(get_db),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    username: Optional[str] = Query(None, description="操作人用户名"),
    operation_type: Optional[str] = Query(None, description="操作类型"),
    success: Optional[int] = Query(None, description="操作结果"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间")
):
    """
    获取操作日志列表
    
    - **page**: 页码
    - **page_size**: 每页数量
    - **username**: 操作人用户名（可选）
    - **operation_type**: 操作类型（可选）
    - **success**: 操作结果（可选）
    - **start_time**: 开始时间（可选）
    - **end_time**: 结束时间（可选）
    """
    try:
        # 构建查询条件
        query = db.query(OperationLogModel)
        
        if username:
            query = query.filter(OperationLogModel.username.contains(username))
        if operation_type:
            query = query.filter(OperationLogModel.operation_type == operation_type)
        if success is not None:
            query = query.filter(OperationLogModel.success == success)
        if start_time:
            query = query.filter(OperationLogModel.operation_time >= start_time)
        if end_time:
            query = query.filter(OperationLogModel.operation_time <= end_time)
        
        # 计算总数
        total = query.count()
        
        # 分页查询
        offset = (page - 1) * page_size
        logs = query.order_by(OperationLogModel.operation_time.desc()).offset(offset).limit(page_size).all()
        
        # 转换为schema格式
        items = []
        for log in logs:
            # 手动构建响应对象，避免Pydantic转换问题
            item = {
                "id": log.id,
                "user_id": log.user_id,
                "username": log.username,
                "ip_address": log.ip_address,
                "operation_type": log.operation_type,
                "operation_content": log.operation_content,
                "content": log.operation_content,  # 兼容前端使用content字段
                "success": log.success,
                "error_message": log.error_message,
                "created_at": log.operation_time
            }
            items.append(item)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "items": items,
                "total": total,
                "page": page,
                "page_size": page_size,
                "pages": (total + page_size - 1) // page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取操作日志失败: {str(e)}")